package android.support.v4.content;

import android.content.Context;

public abstract class DefaultAsyncTaskLoader<Result> extends AsyncTaskLoader<Result> {
    public DefaultAsyncTaskLoader(Context context) {
		super(context);
	}
    
    private Result result;
    private boolean isRunning;
    
    /* Runs on the UI thread */
    @Override
    public void deliverResult(Result result) {
        if (isReset()) {
            return;
        }
        if (isStarted()) {
            super.deliverResult(result);
        }
    }
    
    protected abstract Result load();

    @Override
	public Result loadInBackground() {
		return (this.result = load());
	}



	/**
     * Starts an asynchronous load of the contacts list data. When the result is ready the callbacks
     * will be called on the UI thread. If a previous load has been completed and is still valid
     * the result may be passed to the callbacks immediately.
     *
     * Must be called from the UI thread
     */
    @Override
    protected void onStartLoading() {
        if (takeContentChanged() || result == null) {
            forceLoad();
        }
    }

    /**
     * Must be called from the UI thread
     */
    @Override
    protected void onStopLoading() {
        cancelLoad();
        result = null;
    }

    @Override
    public void onCanceled(Result result) {
        result = null;
    }

    @Override
    protected void onReset() {
        super.onReset();
        
        // Ensure the loader is stopped
        onStopLoading();
        result = null;
    }
}
